package ulmermark.demo.concurrency.core.inbox;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import ulmermark.demo.concurrency.core.Target;


public class DedicatedInbox implements Inbox {
	
	private static final Logger LOGGER = Logger.getLogger( DedicatedInbox.class);

	private final ExecutorService executor = Executors.newSingleThreadExecutor();
	private BlockingQueue<Callback> queue = new LinkedBlockingQueue<Callback>();
	
	private  final String name;
	
	public DedicatedInbox(String name) {
		this.name = name;
		executor.execute(new Runnable(){
			public void run(){
				  for (;;) {  //run forever, dequeue callbacks
					  try {
						  final Callback cb = queue.take();
						  cb.getTarget().received(cb.getPayload());
					  } catch (Exception e) {
						  LOGGER.error(e.getMessage(), e);					  }
				  }
				}
			}
		);
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public <T> void deliver(final Target<T> target, final T payload) {
		final Callback cb = new Callback<T>( target, payload);
		queue.add(cb);
	}

}
